package org.example.trigger.listener;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.example.domain.user_raffle.model.event.message.StockZeroMessage;
import org.example.domain.user_raffle.service.IUserRaffleService;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author lxc18
 * @date 2025/4/2 11:39
 * @description UpdateStockZeroListener
 */
@Component
@Slf4j
public class UpdateStockZeroListener {

    @Resource
    private IUserRaffleService userRaffleService;
    @RabbitListener(queues = "stock-zero-queue")  // 监听 update_stock_zero 队列
    public void handleStockZeroMessage(String messageJson) {
        // 解析消息
        StockZeroMessage message = JSON.parseObject(messageJson, StockZeroMessage.class);
        log.info("收到库存清零消息: " + message.getPrizeId());
        // 处理库存清零逻辑，例如更新数据库
        //先进行判断，是否重复消费
        if (userRaffleService.isTaskStockZero(message.getId())) {
            log.info("库存清零消息重复消费: " + message.getPrizeId());
            return;
        }
        try {
            userRaffleService.updateStockToZero(message.getPrizeId());
            log.info("库存清零成功: " + message.getPrizeId());
            //状态更改
            userRaffleService.updateStatusSuccess(message.getId());
        }
        catch (Exception e) {
            log.error("更新库存失败", e);
            //状态更改
            userRaffleService.updateStatusFailed(message.getId());
        }
    }
}
